package com.hanthink.system.service.photoalbum.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanthink.system.domain.model.PhotoAlbumModel;
import com.hanthink.system.domain.protocol.photoalbum.PhotoAlbumAddRequest;
import com.hanthink.system.domain.protocol.photoalbum.PhotoAlbumPageRequest;
import com.hanthink.system.domain.protocol.photoalbum.PhotoAlbumPageResponse;
import com.hanthink.system.mapper.photoalbum.PhotoAlbumMapper;
import com.hanthink.system.service.photoalbum.PhotoAlbumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 相册业务逻辑层
 *
 * @author WangBin
 * @date 2025-08-20
 */
@Slf4j
@Service
public class PhotoAlbumServiceImpl extends ServiceImpl<PhotoAlbumMapper, PhotoAlbumModel> implements PhotoAlbumService {

    @Autowired
    private PhotoAlbumMapper photoAlbumMapper;

    private String generateSnowflakeId() {
        return String.valueOf(com.baomidou.mybatisplus.core.toolkit.IdWorker.getId());
    }

    /**
     * 保存相册数据
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean savePhotoAlbum(PhotoAlbumAddRequest request) {
        boolean isSuccess = false;
        List<PhotoAlbumModel> list = new ArrayList<>();
        String userId = request.getUserId();
        // 处理图片
        if (request.getPicList() != null && !request.getPicList().isEmpty()) {
            request.getPicList().forEach(url -> {
                PhotoAlbumModel model = createModel(url, "1", userId);
                list.add(model);
            });
        }
        // 处理视频
        if (request.getVideoList() != null && !request.getVideoList().isEmpty()) {
            request.getVideoList().forEach(url -> {
                PhotoAlbumModel model = createModel(url, "2", userId);
                list.add(model);
            });
        }
        // 批量保存
        if (!list.isEmpty()) {
            int result = photoAlbumMapper.batchInsertPhotoAlbum(list);
            isSuccess = result > 0;
            // 保存成功后判断寄存总量是否大于50条数据
            if (isSuccess) {
                PhotoAlbumPageRequest requestPage = new PhotoAlbumPageRequest();
                requestPage.setCreatorId(userId);
                List<PhotoAlbumPageResponse> photoAlbumList = photoAlbumMapper.selectPhotoAlbumPage(requestPage);

                // 超过则作废时间最早的，保留50条
                if (photoAlbumList.size() > 50) {
                    // 获取需要删除的ID列表（从第51条开始的所有数据）
                    List<String> idsToDelete = photoAlbumList.stream()
                            .skip(50) // 跳过前50条（保留最新的50条）
                            .map(PhotoAlbumPageResponse::getId) // 提取ID
                            .collect(Collectors.toList());

                    // 调用删除方法
                    if (!idsToDelete.isEmpty()) {
                        boolean deleteSuccess = cancelPhotoAlbum(idsToDelete);
                        if (deleteSuccess) {
                            log.info("成功删除{}条最早的相册数据", idsToDelete.size());
                        } else {
                            log.warn("删除最早的相册数据失败");
                        }
                    }
                }
            }
        }
        return isSuccess;
    }

    /**
     * 获取相册列表数据
     *
     * @param request
     * @return
     */
    @Override
    public List<PhotoAlbumPageResponse> getPhotoAlbumPage(PhotoAlbumPageRequest request) {
        return photoAlbumMapper.selectPhotoAlbumPage(request);
    }

    /**
     * 赋值处理
     *
     * @param url
     * @param type
     * @return
     */
    private PhotoAlbumModel createModel(String url, String type, String userId) {
        PhotoAlbumModel model = new PhotoAlbumModel();
        model.setId(generateSnowflakeId());
        model.setUrl(url);
        model.setType(type);
        model.setCreateTime(System.currentTimeMillis());
        model.setUpdateTime(System.currentTimeMillis());
        model.setCreatorId(userId);
        return model;
    }

    /**
     * 删除相册数据
     *
     * @param ids 主键
     * @return 状态
     */
    @Override
    public boolean cancelPhotoAlbum(List<String> ids) {
        boolean isSuccess = false;
        if (!ids.isEmpty()) {
            int result = photoAlbumMapper.batchCancelPhotoAlbum(ids, System.currentTimeMillis());
            isSuccess = result > 0;
        }
        return isSuccess;
    }

}
